package com.zmx.doctor.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.itingchunyu.badgeview.BadgeTextView;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.doctor.MyApplication;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.ArticleMessageAdapter;
import com.zmx.doctor.adapter.BooksRecommendedAdapter;
import com.zmx.doctor.adapter.FriendsLiveAdapter;
import com.zmx.doctor.adapter.TripGridviewadapter;
import com.zmx.doctor.listener.InformUpdateListenerManager;
import com.zmx.doctor.listener.MessageUpdateListener;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.ArticleMessage;
import com.zmx.doctor.pojo.TripDay;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.activity.ArticleDetailsActivity;
import com.zmx.doctor.view.activity.ArticleListActivity;
import com.zmx.doctor.view.activity.CelebrityActivity;
import com.zmx.doctor.view.activity.CircleOfFriendsActivity;
import com.zmx.doctor.view.activity.DiseaseSearchActivity;
import com.zmx.doctor.view.activity.ExpertConsultationActivity;
import com.zmx.doctor.view.activity.ExpertTeamActivity;
import com.zmx.doctor.view.activity.LiveSetActivity;
import com.zmx.doctor.view.activity.MessageActivity;
import com.zmx.doctor.view.activity.MyClinicActivity;
import com.zmx.doctor.view.activity.PatientMessageActivity;
import com.zmx.doctor.view.activity.PhysicianListActivity;
import com.zmx.doctor.view.activity.PrescriptionMouldActivity;
import com.zmx.doctor.view.activity.RegistrationListActivity;
import com.zmx.doctor.view.activity.TripActivity;
import com.zmx.doctor.view.util.CustomTextSwitcher;
import com.zmx.doctor.view.util.MySharedPreferences;
import com.zmx.doctor.wangyiyun.permission.MPermission;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * 时间：2020/5/5 14:26
 * 功能：
 */
public class OneFrgment extends SimpleImmersionFragment {

    private RelativeLayout relative1, relative2, relative3;

    private RelativeLayout prescription_template, patient_message, set_gh, set_wz;
    private CustomTextSwitcher tvDownUpTextSwitcher;
    private TextView my_clinic, expert_consultation, live_set, text_discuss,message_button,number_remaining,complete_number,compre,askMonth,examine_time,delivery_time;

    private ArticleMessageAdapter messageAdapter;
    private List<ArticleMessage> lists;
    private List<ArticleMessage> images;
    private RecyclerView re_doctor;

    private static BadgeTextView mBadgeView;


    private EditText search;

//    private TripGridviewadapter gridviewadapter;
//    private List<TripDay> tripDays;
//    private GridView gridview;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);

        requestBasicPermission();
        authorityManage();

        //接口InformUpdateListener的实现方法，监听数据更新中是否有首页图片更新
        InformUpdateListenerManager informUpdateListenerManager = new InformUpdateListenerManager(this.getActivity());
        informUpdateListenerManager.getInstance(this.getActivity()).setInformUpdateListener(new MyInformUpdateListener(this.getActivity()));

        number_remaining = view.findViewById(R.id.number_remaining);
        complete_number = view.findViewById(R.id.complete_number);
        compre = view.findViewById(R.id.compre);
        askMonth = view.findViewById(R.id.askMonth);
        delivery_time = view.findViewById(R.id.delivery_time);
        examine_time = view.findViewById(R.id.examine_time);

        message_button = view.findViewById(R.id.message_button);
        mBadgeView = new BadgeTextView(this.getContext());
        mBadgeView  = new BadgeTextView(this.getContext());

        mBadgeView.setTargetView(message_button);//设置目标targetView(可任意:此处只做演示)
        mBadgeView.setBadgeCount(0)//数量(0:表示小红点)
                .setmDefaultRightPadding(10)//右依附视图距离
                .setmDefaultTopPadding(10);//上依附视图距离

        if (MyApplication.unread_message()) {

            mBadgeView.setVisibility(View.VISIBLE);

        }else{

            mBadgeView.setVisibility(View.GONE);
        }

        message_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    mBadgeView.setVisibility(View.GONE);
                    Intent intent = new Intent();
                    intent.setClass(OneFrgment.this.getContext(), MessageActivity.class);
                    startActivity(intent);


            }
        });

        prescription_template = view.findViewById(R.id.prescription_template);
        prescription_template.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.putExtra("logo","0");
            intent.setClass(OneFrgment.this.getContext(), PrescriptionMouldActivity.class);
            startActivity(intent);
        });
        patient_message = view.findViewById(R.id.patient_message);
        patient_message.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(OneFrgment.this.getContext(), PatientMessageActivity.class);
            startActivity(intent);
        });

        set_gh = view.findViewById(R.id.set_gh);
        set_gh.setOnClickListener(v -> {

            Intent intent = new Intent();
            intent.setClass(OneFrgment.this.getContext(), RegistrationListActivity.class);
            startActivity(intent);


        });
        set_wz = view.findViewById(R.id.set_wz);
        set_wz.setOnClickListener(v -> {

            Intent intent = new Intent();
            intent.setClass(OneFrgment.this.getContext(), ExpertTeamActivity.class);
            startActivity(intent);


        });

        relative1 = view.findViewById(R.id.relative1);
        relative1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(OneFrgment.this.getContext(), ArticleListActivity.class);
                intent.putExtra("client", "3");
                intent.putExtra("name", "中医经方");
                startActivity(intent);

            }
        });

        search = view.findViewById(R.id.search);
        search.setFocusable(false);
        search.setOnClickListener(v -> {

            Intent intent = new Intent();
            intent.setClass(OneFrgment.this.getContext(), DiseaseSearchActivity.class);
            startActivity(intent);

        });

        expert_consultation = view.findViewById(R.id.expert_consultation);
        expert_consultation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(OneFrgment.this.getContext(), ExpertConsultationActivity.class);
                startActivity(intent);
            }
        });

        text_discuss = view.findViewById(R.id.text_discuss);
        text_discuss.setOnClickListener(v -> {

            Intent intent = new Intent(OneFrgment.this.getContext(), CircleOfFriendsActivity.class);
            startActivity(intent);
        });
        live_set = view.findViewById(R.id.live_set);
        live_set.setOnClickListener(v -> {

            Intent intent = new Intent(OneFrgment.this.getContext(), LiveSetActivity.class);
            startActivity(intent);
        });

        relative2 = view.findViewById(R.id.relative2);
        relative2.setOnClickListener(v -> {


            Intent intent = new Intent(OneFrgment.this.getContext(), ArticleListActivity.class);
            intent.putExtra("client", "4");
            intent.putExtra("name", "老中医经验");
            startActivity(intent);
        });

        relative3 = view.findViewById(R.id.relative3);
        relative3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent intent = new Intent(OneFrgment.this.getContext(), ArticleListActivity.class);
                intent.putExtra("client", "5");
                intent.putExtra("name", "疾病新闻");
                startActivity(intent);
            }
        });



        //走马灯
        tvDownUpTextSwitcher = view.findViewById(R.id.tvDownUpTextSwitcher);
        String[] data = new String[]{"最伤肾中药“黑名单”，肾病患者千万别犯", "最伤肾中药“黑名单”，肾病患者千万别犯", "最伤肾中药“黑名单”，肾病患者千万别犯", "最伤肾中药“黑名单”，肾病患者千万别犯"};
        // 上下滚动
        tvDownUpTextSwitcher.setInAnimation(R.anim.animation_down_up_in_animation)
                .setOutAnimation(R.anim.animation_down_up_out_animation)
                .bindData(data)
                .startSwitch(2000L);

        my_clinic = view.findViewById(R.id.my_clinic);
        my_clinic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(OneFrgment.this.getContext(), TripActivity.class);
                startActivity(intent);

            }
        });

        messageAdapter = new ArticleMessageAdapter(this.getActivity());
        re_doctor = view.findViewById(R.id.re_doctor);
        re_doctor.setLayoutManager(new LinearLayoutManager(this.getContext()));
        re_doctor.setAdapter(messageAdapter);
        lists = new ArrayList<>();
        messageAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                //目前Activity→目标Activity
//                Log.e("范德萨发发","放到"+lists.get(listPosition).getTitle());
                Intent intent = new Intent(OneFrgment.this.getContext(), ArticleDetailsActivity.class);
                intent.putExtra("am", lists.get(listPosition));
                startActivity(intent);
            }
        });
        getData();
        getColumn();
        getDatas();
        return view;
    }


    /**
     * 权限申请
     */
    private void authorityManage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(OneFrgment.this.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(OneFrgment.this.getActivity(),
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        1);
            } else {
                Toast.makeText(OneFrgment.this.getContext(), "权限已申请", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private static final int BASIC_PERMISSION_REQUEST_CODE = 100;

    private void requestBasicPermission() {
        MPermission.printMPermissionResult(true, OneFrgment.this.getActivity(), BASIC_PERMISSIONS);
        MPermission.with(OneFrgment.this.getActivity())
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS)
                .request();
    }

    /**
     * 基本权限管理
     */
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray array = object.getJSONArray("data");

                        Gson gson = new Gson();
                        for (int i = 0; i < array.length(); i++) {

                            JSONObject jsonObject = array.getJSONObject(i);
                            ArticleMessage articleMessage = gson.fromJson(jsonObject.toString(), ArticleMessage.class);
                            lists.add(articleMessage);

                        }
                        messageAdapter.setListAndNotifyDataSetChanged(lists);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Log.e("数据",object.toString());

                        JSONObject data = object.getJSONObject("data");
                        number_remaining.setText(data.getString("askTodayNum")+"个");
                        complete_number.setText(data.getString("askMonth")+"个");
                        compre.setText(data.getString("compre")+"%");
                        askMonth.setText(data.getString("askMonth")+"个");
                        delivery_time.setText(data.getString("todayComment")+"次");
                        examine_time.setText(data.getString("monthComment")+"次");

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };


    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this).titleBarMarginTop(R.id.toolbar).statusBarDarkFont(true).init();
    }

    public void getData() {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("data[row]", 1 + "");
        params.put("data[number]", 3 + "");
        params.put("data[client]", 3 + "");
        params.put("cmd", "getAllArticle");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/article/", params, handler, 1, 404);

    }
    /**
     * 获取所有提问
     */
    public void getDatas() {

        List<String> ls = new ArrayList<>();
        ls.add(MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, ""));
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("data[member_id]", MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, ""));
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.doctor/getDatas", params, handler, 3, 404);

    }

    //签名
    public String sing(List<String> list) {

        StringBuilder requestparams = new StringBuilder();

        requestparams.append(MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.uid, "") +
                MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.role, "") +
                System.currentTimeMillis() / 1000 + MySharedPreferences.getInstance(this.getActivity()).getString(MySharedPreferences.password, ""));

        if (list != null) {
            for (String s : list) {
                requestparams.append(s);
            }
        }
        return requestparams.toString();
    }

    public void getColumn() {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("data[client]", 3 + "");
        params.put("cmd", "getColumn");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/article/", params, handler, 2, 404);

    }

    private static List<TripDay> getWeekDay() {
        Calendar calendar = Calendar.getInstance();
        // 获取本周的第一天
        int firstDayOfWeek = calendar.getFirstDayOfWeek();
        List<TripDay> list = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            calendar.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + i);
            TripDay weekDay = new TripDay();
            // 获取星期的显示名称，例如：周一、星期一、Monday等等
            weekDay.setWeek(calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.CHINA));
            weekDay.setDay(new SimpleDateFormat("dd").format(calendar.getTime()));
            weekDay.setDate(calendar.getTime());

            list.add(weekDay);
        }

        return list;
    }

    //静态内部类实现接口监听
    static class MyInformUpdateListener implements MessageUpdateListener {
        private WeakReference<Activity> mWeakReference;
        public MyInformUpdateListener(Activity activity){
            Log.e("有消息进来了1","有消息进来了1");
            mWeakReference = new WeakReference<Activity>(activity);//使用弱引用引用外部Activity对象
        }

        @Override
        public void updateMessage() {

            Log.e("有消息进来了","有消息进来了");
            mBadgeView.setVisibility(View.VISIBLE);

        }
    }

}
